const JwtStrategy = require('passport-jwt').Strategy
const ExtractJwt = require('passport-jwt').ExtractJwt
const models = require('./../db/mysqldb/index')
const opts = {}
const config = require('./../config')

opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
opts.secretOrKey = config.secretOrKey
const noLimit = ['/admin-index/statistics', '/admin-user/info']

module.exports = passport => {
  passport.use(
    new JwtStrategy(opts, async function (jwtPayload, done) {
      try {
        if (jwtPayload.type === 'admin') {
          const { role_id } = jwtPayload
          if (role_id && role_id !== config.SUPER_ROLE_ID) {
            // 获取请求地址
            let adminUrl = ''
            if (url.indexOf('?')) {
              adminUrl = url.split('?')[0]
            } else {
              adminUrl = url
            }
            // 处理请求地址
            const authority_url = adminUrl.split(`/api-admin/${config.API_VERSION}`)[1]
            // 根据请求地址查询权限表 获取请求地址的表数据
            let oneAdminAuthority = await models.admin_authority.findOne({
              where: { authority_url }
            })
            if (oneAdminAuthority) {
              // 根据角色id查询角色表
              let oneAdminRole = await models.admin_role.findOne({
                where: {
                  role_id: role_id
                }
              })
              // 判断请求地址的角色id是否在此角色的id字段中
              if (oneAdminRole.admin_authority_ids.indexOf(oneAdminAuthority.authority_id)) {
                return done(null, jwtPayload)
              } else {
                return false
              }
            } else if (noLimit.indexOf(authority_url)) {
              return done(null, jwtPayload)
            } else {
              return false
            }
          } else {
            if (role_id === config.SUPER_ROLE_ID) {
              return done(null, jwtPayload)
            } else {
              return false
            }
          }
        }
      } catch (err) {
        console.log(err)
        return false
      }
    })
  )
}
